﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

public class GameManager : MonoBehaviour {
    public float levelStartDelay = 2f;

    public BoardManager boardScript;

    public int playerFoodPoints = 100;
    [HideInInspector]public bool playersTurn = true;

    private int level = 3;
    private Text levelText;
    private GameObject levelImage;
    public static GameManager instnce = null;
    private bool doingSetup;
    public float turnDelay = 0.1f;

    private List<Enemy> enemies;
    private bool enemiesMoving;

    private void OnLevelWasLoaded(int index)
    {
        level++;
        print("1");
        InitGame();
    }

	// Use this for initialization
	void Awake () {

        if (instnce == null)
            instnce = this;
        else if (instnce != this)
            Destroy(gameObject);

        DontDestroyOnLoad(gameObject);//切换场景时不被销毁
        enemies = new List<Enemy>();
        boardScript = GetComponent<BoardManager>();
        print("2");
        InitGame();

	}

    void Update()
    {
        if (playersTurn || enemiesMoving || doingSetup)
            return;
        StartCoroutine(MoveEnemies());
    }

    void InitGame()
    {
        doingSetup = true;
        print("3");
        levelImage = GameObject.Find("levelImage");
        levelText = GameObject.Find("levelText").GetComponent<Text>();
        levelText.text = "Day " + level;
        levelImage.SetActive(true);
        Invoke("HideLevelImage", levelStartDelay);
        
        enemies.Clear();
        boardScript.SetupScene(level);
    }

    void HideLevelImage()
    {
        levelImage.SetActive(false);
        doingSetup = false;
    }

    public void GameOver()
    {
        levelText.text = "After " + level + " days, you starved.";
        levelImage.SetActive(true);
        enabled = false;
    }

    public void AddEnemyToList(Enemy script)
    {
        enemies.Add(script);
    }

    IEnumerator MoveEnemies()
    {
        enemiesMoving = true;

        yield return new WaitForSeconds(turnDelay);

        if (enemies.Count == 0)
        {
            yield return new WaitForSeconds(turnDelay);

        }

        for (int i = 0; i < enemies.Count; i++)
        {
            enemies[i].MoveEnemy();
            yield return new WaitForSeconds(enemies[i].moveTime);
        }

        playersTurn = true;
        enemiesMoving = false;

    }
}
